const BaseService = require('./base_service.js');
const ThirdPartyCouponModel = require('../model/third_party_coupon_model.js');
const CouponVerificationLogModel = require('../model/coupon_verification_log_model.js');

class CouponVerificationService extends BaseService {

  /**
   * 验证券码
   */
  async verifyCoupon(input) {
    const db = uniCloud.database();
    const couponCollection = db.collection(ThirdPartyCouponModel.CL);
    const logCollection = db.collection(CouponVerificationLogModel.CL);

    // 查找券码
    const coupon = await couponCollection.where({
      couponCode: input.couponCode,
      platform: input.platform
    }).get();

    if (!coupon.data.length) {
      // 记录验券失败日志
      await this.recordVerificationLog({
        couponId: null,
        couponCode: input.couponCode,
        platform: input.platform,
        verifyResult: 0,
        verifyMessage: '券码不存在',
        orderAmount: input.orderAmount,
        storeId: input.storeId
      });

      throw new Error('券码不存在');
    }

    const couponData = coupon.data[0];

    // 检查券码状态
    if (couponData.status !== 1) {
      let message = '券码无效';
      if (couponData.status === 2) {
        message = '券码已过期';
      }

      await this.recordVerificationLog({
        couponId: couponData._id,
        couponCode: input.couponCode,
        platform: input.platform,
        verifyResult: 0,
        verifyMessage: message,
        orderAmount: input.orderAmount,
        storeId: input.storeId
      });

      throw new Error(message);
    }

    // 检查是否已使用
    if (couponData.isUsed) {
      await this.recordVerificationLog({
        couponId: couponData._id,
        couponCode: input.couponCode,
        platform: input.platform,
        verifyResult: 0,
        verifyMessage: '券码已使用',
        orderAmount: input.orderAmount,
        storeId: input.storeId
      });

      throw new Error('券码已使用');
    }

    // 检查使用次数限制
    if (couponData.usedCount >= couponData.useLimit) {
      await this.recordVerificationLog({
        couponId: couponData._id,
        couponCode: input.couponCode,
        platform: input.platform,
        verifyResult: 0,
        verifyMessage: '券码使用次数已达上限',
        orderAmount: input.orderAmount,
        storeId: input.storeId
      });

      throw new Error('券码使用次数已达上限');
    }

    // 检查最低消费金额
    if (couponData.minAmount && input.orderAmount < couponData.minAmount) {
      await this.recordVerificationLog({
        couponId: couponData._id,
        couponCode: input.couponCode,
        platform: input.platform,
        verifyResult: 0,
        verifyMessage: `订单金额不足，最低消费${couponData.minAmount / 100}元`,
        orderAmount: input.orderAmount,
        storeId: input.storeId
      });

      throw new Error(`订单金额不足，最低消费${couponData.minAmount / 100}元`);
    }

    // 计算优惠金额
    let discountAmount = 0;
    if (couponData.couponType === 'discount') {
      // 折扣券
      discountAmount = Math.round(input.orderAmount * couponData.discountRate);
      if (couponData.maxDiscount) {
        discountAmount = Math.min(discountAmount, couponData.maxDiscount);
      }
    } else if (couponData.couponType === 'cash') {
      // 代金券
      discountAmount = couponData.couponValue;
    }

    const finalAmount = Math.max(0, input.orderAmount - discountAmount);

    // 更新券码使用状态
    await couponCollection.doc(couponData._id).update({
      isUsed: true,
      usedTime: Date.now(),
      usedCount: couponData.usedCount + 1,
      updateTime: Date.now()
    });

    // 记录验券成功日志
    await this.recordVerificationLog({
      couponId: couponData._id,
      couponCode: input.couponCode,
      platform: input.platform,
      verifyResult: 1,
      verifyMessage: '验券成功',
      orderAmount: input.orderAmount,
      discountAmount: discountAmount,
      finalAmount: finalAmount,
      storeId: input.storeId
    });

    return {
      success: true,
      couponData: {
        couponName: couponData.couponName,
        couponType: couponData.couponType,
        discountAmount: discountAmount,
        finalAmount: finalAmount,
        validFrom: couponData.validFrom,
        validTo: couponData.validTo
      }
    };
  }

  /**
   * 获取券码列表
   */
  async getCouponList(input) {
    const db = uniCloud.database();
    const collection = db.collection(ThirdPartyCouponModel.CL);

    // 构建查询条件
    let whereCondition = {};
    
    if (input.platform) {
      whereCondition.platform = input.platform;
    }
    
    if (input.status !== undefined) {
      whereCondition.status = input.status;
    }
    
    if (input.search) {
      whereCondition.couponCode = new RegExp(input.search, 'i');
    }

    // 分页查询
    const result = await collection
      .where(whereCondition)
      .orderBy('createTime', 'desc')
      .skip((input.page - 1) * input.size)
      .limit(input.size)
      .get();

    // 获取总数
    const countResult = await collection.where(whereCondition).count();

    return {
      list: result.data,
      total: countResult.total,
      page: input.page,
      size: input.size
    };
  }

  /**
   * 获取验券记录
   */
  async getVerificationLogs(input) {
    const db = uniCloud.database();
    const collection = db.collection(CouponVerificationLogModel.CL);

    // 构建查询条件
    let whereCondition = {};
    
    if (input.couponId) {
      whereCondition.couponId = input.couponId;
    }
    
    if (input.platform) {
      whereCondition.platform = input.platform;
    }
    
    if (input.dateRange) {
      const dates = input.dateRange.split(',');
      if (dates.length === 2) {
        whereCondition.verifyTime = db.command.gte(parseInt(dates[0])).and(db.command.lte(parseInt(dates[1])));
      }
    }

    // 分页查询
    const result = await collection
      .where(whereCondition)
      .orderBy('verifyTime', 'desc')
      .skip((input.page - 1) * input.size)
      .limit(input.size)
      .get();

    // 获取总数
    const countResult = await collection.where(whereCondition).count();

    return {
      list: result.data,
      total: countResult.total,
      page: input.page,
      size: input.size
    };
  }

  /**
   * 记录验券日志
   */
  async recordVerificationLog(logData) {
    const db = uniCloud.database();
    const collection = db.collection(CouponVerificationLogModel.CL);

    const logRecord = {
      couponId: logData.couponId,
      couponCode: logData.couponCode,
      platform: logData.platform,
      verifyTime: Date.now(),
      verifyBy: this.getCurrentAdminId(),
      verifyResult: logData.verifyResult,
      verifyMessage: logData.verifyMessage,
      orderAmount: logData.orderAmount,
      discountAmount: logData.discountAmount || 0,
      finalAmount: logData.finalAmount || logData.orderAmount,
      storeId: logData.storeId,
      createTime: Date.now(),
      updateTime: Date.now()
    };

    await collection.add(logRecord);
  }

  /**
   * 获取当前管理员ID
   */
  getCurrentAdminId() {
    // 这里应该从请求上下文中获取当前管理员ID
    return 'admin_001';
  }
}

module.exports = CouponVerificationService;
